package dsync

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

type HttpHandler struct {
	root string
	site string
}

func HttpServer() {
	log.Println("Http Server已启动, 端口:", App.Port)
	if Cfg.Sync.Ddns {
		var ch = make(chan int, 1)
		go openHttpServer(Cfg.Rkws, ch)
		<-ch
	} else {
		openHttpServer(Cfg.Rkws, nil)
	}
}

func (m *HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	path := req.URL.Path
	//log.Println("====================path", path)
	//log.Printf("httpHandler : %+v\n", m)
	if path == "" || path == "/" {
		http.ServeFile(res, req, "./index.html")
		return
	}
	last := path[len(path)-1:]
	if last == "" {
		path = fmt.Sprint(path, "/index.html")
	} else if last == "/" {
		path = fmt.Sprint(path, "index.html")
	}
	file := fmt.Sprint("./", m.root, path)
	//log.Println("file:", file)
	f, err := os.Open(file)
	if err != nil {
		//log.Println("error not page:", path, err)
		http.ServeFile(res, req, "./404.html")
		return
	}
	defer f.Close()
	if IsDir(file) {
		//log.Println("文件夹")
		http.ServeFile(res, req, "./404.html")
	} else {
		//log.Println("文件")
		http.ServeFile(res, req, file)
	}
}

func openHttpServer(rkws []Rkw, ch chan int) {
	hh := &HttpHandler{
		root: "/",
		site: "/",
	}
	http.Handle("/", hh)
	for _, v := range rkws {
		for _, site := range v.Sites {
			site = fmt.Sprint("/", site, "/")
			dir := fmt.Sprint("./", v.RR, site)
			log.Println("域名:", v.RR, "网站:", site, "- 解析目录:", dir)
			hh := &HttpHandler{
				root: v.RR,
				site: site,
			}
			http.Handle(site, hh)
		}
	}

	hs := http.Server{
		Addr:           ":" + App.Port,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	if ch != nil {
		ch <- 1
	}
	err := hs.ListenAndServe()
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
